<?php
if (!class_exists('AlfaFilterChain')) {
	
	/**
	 * @author Alecsandru Gabriel DINU
	 * @since Jun 12, 2008
	 * Filter chain class. This class takes care of invoking
	 * filters defined in config.xml.
	 */
	class AlfaFilterChain  {
	  	protected $filterConfig;
		
		/**
		 * Class constructor.
		 * @access public
		 */
		public function __construct() {
			$config = AlfaConfiguration::getInstance();
			$filters = $config->get("filters/filter");
			if (isset($filters) && sizeof($filters) > 0) {
				$filters =& array_reverse($filters);
			}
			$this->filterConfig = new AlfaFilterConfig();
			$this->filterConfig->setFilters(& $filters);
		}
		
		/**
		 * Returns the filter config.
		 * @access public
		 * @return AlfaFilterConfig 
		 */
		public function getFilterConfig() {
			return $this->filterConfig;
		}
		
		/**
		 * Performs the filtering.
		 * @access public
		 * @param AlfaFilterChain
		 */
		public function doFilter(Context $context) {
			$filters =& $this->filterConfig->getFilters();
			if (isset($filters) && sizeof($filters) > 0) {
				$currentFilter = array_pop($filters);
				$this->filterConfig->setFilters(& $filters);
				
				$filterClass = $currentFilter->xpath("class");
				$filterClass = (string)$filterClass[0];

				$filterFile = $currentFilter->xpath("file");
				$filterFile = (string)$filterFile[0];
				
				$initParams = $currentFilter["init-param"];
				
				
				include_once($filterFile);
				// Create an instance of the ReflectionClass class
				$class = new ReflectionClass($filterClass);
				// If this class is instantiable, create an instance
				if ($class->isInstantiable()) {
				    $filter = $class->newInstance(& $this->filterConfig);
				    $filter->init();
				    $filter->doFilter(&$context, &$this);
				}
			}
		}
	}
}